<template>
    <div @click="drawer = true">
        <el-icon :size="28" color="#fff">
            <MagicStick />
        </el-icon>
    </div>
    <el-drawer v-model="drawer" title="设置主题">
        <span>自定义主题</span>
        <div class="custom">
            <div class="theme">
                <span>主题色：</span>
                <el-color-picker v-model="themeColor" show-alpha @change="changeThemeColor" />
                <span>{{ themeColor }}</span>
            </div>
            <div class="subTheme">
                <span>副题色：</span>
                <el-color-picker v-model="subThemeColor" show-alpha @change="changeSubThemeColor" />
                <span>{{ subThemeColor }}</span>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button :color="themeColor" primary @click="reset">重置</el-button>
            </div>
        </template>
    </el-drawer>
</template>
<script setup name="themeIcon">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router'

const router = useRouter()
const num = ref(-1)
const drawer = ref(false)
const themeColor = ref(getComputedStyle(document.documentElement).getPropertyValue('--theme-color'))
const subThemeColor = ref(getComputedStyle(document.documentElement).getPropertyValue('--sub-theme-color'))
const changeThemeColor = (value, index) => {
    if (index === undefined) {
        num.value = -1
    } else {
        num.value = index
    }
    themeColor.value = value
    document.documentElement.style.setProperty('--theme-color', themeColor.value)
    localStorage.setItem('theme-color', themeColor.value)
    router.go(0)
}

const changeSubThemeColor = (value, index) => {
    if (index === undefined) {
        num.value = -1
    } else {
        num.value = index
    }
    subThemeColor.value = value
    document.documentElement.style.setProperty('--sub-theme-color', subThemeColor.value)
    localStorage.setItem('sub-theme-color', subThemeColor.value)
    router.go(0)
}

const reset = () => {
    localStorage.removeItem('theme-color')
    localStorage.removeItem('sub-theme-color')
    router.go(0)
}

onMounted(() => {
    const theme = localStorage.getItem('theme-color')
    const subTheme = localStorage.getItem('sub-theme-color')
    if (theme) {
        themeColor.value = theme
    }
    if (subTheme) {
        subThemeColor.value = subTheme
    }
})
</script>
<style lang='less' scoped>
.custom {
    margin-top: 20px;
    margin-left: 12px;

    .theme,
    .subTheme {
        display: flex;
        justify-content: left;
        align-items: center;
        gap: 20px;
        margin-bottom: 20px;
    }
}
</style>